package com.leiy.crawlerjd.util;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.UUID;

@Component
public class HttpUtils {

    private  PoolingHttpClientConnectionManager cm;

    public HttpUtils(){
        cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(100);
        cm.setDefaultMaxPerRoute(10);
    }

    /**
     * 根据请求地址下载页面数据
     * @param url
     * @return
     */
    public String doGetHtml(String url) {
        CloseableHttpResponse response = null;
        try{
            // 判断响应体是否不为空,  设置字符编码
            response = this.getResponse(url);
            if (response != null && response.getEntity() != null) {
                try {
                    return EntityUtils.toString(response.getEntity(), "utf8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(response!=null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    /**
     * 下载图片
     * @param url
     * @return
     */
    public String doGetImage(String url) {

        CloseableHttpResponse response = null;
        try{
            // 判断响应体是否不为空,  设置字符编码
            //HttpEntity enitity = this.getEntity(url);
            response = this.getResponse(url);
            if (response.getEntity() == null) {
                return "";
            }
            // 下载图片
            // 获取图片后缀
            String ext = url.substring(url.lastIndexOf('.')); // getFormatInUrl(url);
            // 创建图片名，重命名图片
            String picName = UUID.randomUUID().toString()+ext;
            // 下载图片
            // 声明OutPutStream
            OutputStream outputStream = new FileOutputStream(new File("/home/leiyun/IdeaProjects/gitdemo/heima/Crawler/crawler-jd/doc/"+picName));
            response.getEntity().writeTo(outputStream);
            // 返回图片名称
            return picName;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(response!=null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

    private CloseableHttpResponse getResponse(String url) {
        HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(cm);
        // 1.打开浏览器器，创建http对象
        CloseableHttpClient httpClient = clientBuilder.build();
        // 2.输入网址，发起get请求创建HttpGet对象
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("user-agent","Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36");
        // 设置请求信息
        httpGet.setConfig(this.getConfig());
        // 3.回车，返回response
        CloseableHttpResponse response = null;
        try {
            // 使用httpClinet发起请求，获取响应
            response=httpClient.execute(httpGet);
            // 解析响应，返回结果
            if(response.getStatusLine().getStatusCode() == 200){
                return response;
            }else{
                System.out.println("==================response异常==============");
                System.out.println(response.getStatusLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     *  设置请求信息
     * @return
     */
    private RequestConfig getConfig() {
        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(2000) // 创建连接 最长时间，毫秒
                .setConnectionRequestTimeout(1000) //  获取连接 最长时间
                .setSocketTimeout(10*1000).build(); // 数据传输 最长时间
        return config;
    }

    /**
     * 获取图片的类型
     * @param url
     * @return
     */
    public static String getFormatInUrl(String url) {
        File f = new File(url);
        if (f.exists()) {
            String ext = getFormatName(f);
            System.out.println(ext);
            return ext;
        }
        return "";
    }
    /**
     * 获取图片的类型
     * @param o
     * @return
     */
    private static String getFormatName(Object o) {
        try {
            // Create an image input stream on the image
            ImageInputStream iis = ImageIO.createImageInputStream(o);

            // Find all image readers that recognize the image format
            Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);
            if (!iter.hasNext()) {
                // No readers found
                return null;
            }

            // Use the first reader
            ImageReader reader = iter.next();

            // Close stream
            iis.close();

            // Return the format name
            return reader.getFormatName();
        } catch (IOException e) {
            //
        }

        // The image could not be read
        return null;
    }
}
